<template>
  <div class="codeView">
    <van-row justify="center" class="logWrap">
      <img alt="鸿康心理" src="../../assets/logo2.png" />
    </van-row>
    <van-form class="login-form" validate-trigger="onSubmit" @submit="onSubmit">
      <van-field
        v-model="loginForm.account"
        class="el-form-item"
        name="account"
        label=""
        :left-icon="userIcon"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="loginForm.password"
        class="el-form-item"
        type="password"
        name="password"
        :left-icon="psIcon"
        label=""
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-row class="regist">
        <van-col span="12" style="text-align: left"
          ><span @click="viewClick('phone')">切换登录方式</span></van-col
        >
        <van-col span="12" style="text-align: right"
          ><span @click="menuClick('Register')">注册</span></van-col
        >
      </van-row>
      <van-button
        color="#61BB83"
        block
        native-type="submit"
        :disabled="logining"
        :loading="logining"
        class="subbtn"
      >
        登录
      </van-button>
    </van-form>
  </div>
</template>

<script>
import { defineComponent, ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  getCaptcha,
  loginByUsername,
  findTenList,
  getTenList,
  changeTenant,
} from '../../api/login/login'
import { setToken, setUser } from '../../util/auth'
import { useStore } from '/@/store'
import userIcon from '../../assets/icon/user.png'
import psIcon from '../../assets/icon/ps.png'
import { Toast } from 'vant'
import { useLoginAfter } from './utils'

export default defineComponent({
  components: {},
  setup(props, context) {
    const router = useRouter()
    const route = useRoute()
    const { commit } = useStore()
    const picker = ref(null)
    const state = reactive({
      value: '',
      showPicker: false,
      loading: true,
      toolbar: true,
    })
    const customFieldName = {
      text: 'tenantName',
      values: 'tenantId',
    }
    const columns = reactive([])
    const logining = ref(false) // 是否登录中
    const loginForm = reactive({
      tenantId: '',
      account: '',
      password: '',
      code: '',
    })
    const captchaObj = reactive({
      image: '',
      key: '',
    })
    getCaptcha().then((res) => {
      captchaObj.image = res.data.data.image
      captchaObj.key = res.data.data.key
    })
    const onConfirm = (item) => {
      state.showPicker = false
      state.value = item.tenantName
      loginForm.tenantId = item.tenantId
    }

    const { loginRedirect } = useLoginAfter()

    return {
      psIcon,
      userIcon,
      loginForm,
      logining,
      state,
      onConfirm,
      columns,
      picker,
      customFieldName,
      onSearch() {
        const query = state.value
        findTenList(query).then((res) => {
          const list = res.data.data
          if (list.length == 0) return
          state.showPicker = true
          setTimeout(function () {
            picker.value.setColumnValues(0, list)
          }, 500)
        })
      },
      menuClick(menuName) {
        // 通过自定义事件回传值
        context.emit('menuClick', { menuName })
      },
      viewClick(menuName) {
        // 通过自定义事件回传值
        context.emit('viewClick', { menuName })
      },
      onSubmit(values) {
        values.grantType = 'captcha'
        values.type = 'account'
        values.key = captchaObj.key
        logining.value = true

        loginByUsername(values)
          .then((res) => {
            const loginfo = res.data.data
            setToken(loginfo.accessToken)
            localStorage.setItem('fock_user_data', JSON.stringify(loginfo))
            getTenList({ account: loginfo.account })
              .then((rep) => {
                const tenList = rep.data.data
                if (tenList && tenList.length > 1) {
                  logining.value = false
                  localStorage.setItem(
                    'fock_user_list',
                    JSON.stringify(tenList)
                  )
                  router.push({
                    name: 'Organization',
                    query: {
                      auhType: 'code',
                    },
                  })
                } else {
                  const param = {
                    roles: loginfo.authority.split(','),
                    oauthId: loginfo.oauthId,
                    user: {
                      id: loginfo.userId,
                      tenantId: tenList[0].tenantId,
                      name: loginfo.userName,
                      realName: loginfo.userName,
                      account: loginfo.account,
                      gradeId: loginfo.gradeId,
                    },
                  }
                  changeTenant(param)
                    .then(async (res) => {
                      const loginfo = res.data.data
                      setToken(loginfo.accessToken)
                      const user = {
                        account: loginfo.account,
                        tenantId: loginfo.tenantId,
                        userId: loginfo.userId,
                        userName: loginfo.userName,
                      }
                      setUser(JSON.stringify(user))
                      commit('setUser', user)
                      if (route.query && route.query.projectId) {
                        router.push({
                          name: 'code-evaluation',
                          query: {
                            projectId: route.query?.projectId,
                          },
                        })
                      } else {
                        await loginRedirect()
                      }

                      logining.value = false
                    })
                    .catch((err) => {
                      logining.value = false
                    })
                }
              })
              .catch((err) => {
                logining.value = false
              })
          })
          .catch((err) => {
            logining.value = false
            Toast('请确认您的账号或密码是否正确！')
          })
      },
    }
  },
  data() {},
  created() {},
  methods: {},
})
</script>

<style lang="less" scoped>
.codeView {
  box-sizing: border-box;
  min-height: calc(100vh - 126px);
  padding: 45px 15px 15px 15px;
}

.logWrap {
  margin-top: 75px;
  margin-bottom: 60px;
  img {
    height: 78px;
  }
}

.login-form {
}

.login-form .el-form-item {
  width: 70vw;
  margin: 0 auto;
  margin-bottom: 12px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.5);
}

/deep/.van-cell::after {
  position: static;
}

.login-form .el-search {
  margin-bottom: 12px;
  opacity: 0.8;
}

.regist {
  width: 70vw;
  margin: 0 auto;
  font-size: 14px;
  padding: 0 15px;
  color: #3071b9;
  color: white;
}

.subbtn {
  width: 70vw;
  margin: 0 auto;
  opacity: 0.8;
  margin-top: 30px;
  border-radius: 5px;
}

/deep/ .van-radio__label {
  color: #3071b9;
}
</style>
